package com.wwwarehouse.common.activity.media;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.custom_widget.media.AttachVideoView;
import com.wwwarehouse.common.custom_widget.media.PlayVideoView;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.PermissionUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ThreadUtils;
import com.wwwarehouse.common.tools.ThumbnailUtils;
import com.wwwarehouse.common.tools.ToastUtils;

import java.io.File;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

public class AttachVideoActivity extends BaseActivity implements PermissionUtils.PermissionCallbacks, View.OnClickListener, EasyPopupWindow.ChildClickListener {
    private ImageView mTopReturn;
    private AttachVideoView mAttachVideoView;
    private PlayVideoView mPlayVideoView;
    private JCVideoPlayerStandard mJCVideoPlayerStandard;

    private EasyPopupWindow mEasyPopupWindow;

    private FileUtils mFileUtils;
    private File mFile;

    private String mVideoUrl = "http://192.168.6.93/pic/309815e0-6bf6-46ed-b8bd-4a6d6134da9d.mp4";

    private static final int REQUEST_ATTACH_VIDEO_CAMERA = 1;
    private static final int REQUEST_ATTACH_VIDEO_GALLERY = 2;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap thumbnailBitmap = (Bitmap) msg.obj;
            mJCVideoPlayerStandard.thumbImageView.setImageBitmap(thumbnailBitmap);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attach_video);

        initView();
        initEvent();
    }

    private void initView() {
        mTopReturn = (ImageView) findViewById(R.id.top_return);

        mAttachVideoView = (AttachVideoView) findViewById(R.id.attach_video_view);

        mPlayVideoView = (PlayVideoView) findViewById(R.id.play_video_view);
        mPlayVideoView.setVideoUrl(mVideoUrl);

        mJCVideoPlayerStandard = (JCVideoPlayerStandard) findViewById(R.id.video_player_standard);

        mJCVideoPlayerStandard.setUp(mVideoUrl, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "这是一个视频");

        ThreadUtils.newThread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumbnailBitmap = ThumbnailUtils.createNetVideoThumbnail(mVideoUrl);

                if (thumbnailBitmap != null) {
                    Message msg = Message.obtain();
                    msg.obj = thumbnailBitmap;
                    mHandler.sendMessage(msg);
                }
            }
        });

        mFileUtils = new FileUtils();
    }

    private void initEvent() {
        mTopReturn.setOnClickListener(this);

        mAttachVideoView.setOnAttachVideoListener(new AttachVideoView.OnAttachVideoListener() {
            @Override
            public void onAttachVideo() {
                mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.attach_video_popupwindow, AttachVideoActivity.this, findViewById(android.R.id.content), true, AttachVideoActivity.this);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> permissionList) {
        //当requestCode相同时候，permissions.size == 请求的权限数时候，认为权限请求成功
        if(requestCode == 1 && permissionList.size() == 1) {
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
            // 根据文件地址创建文件
            mFile = mFileUtils.getVideosFile("VID_" + DateUtil.formatDate(System.currentTimeMillis(), "yyyyMMdd_HHmmss") + ".mp4");

            Uri uri;

            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + BuildConfig.ProviderSuffix, mFile);
            } else {
                // 把文件地址转换成Uri格式
                uri = Uri.fromFile(mFile);
            }

            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_ATTACH_VIDEO_CAMERA);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ATTACH_VIDEO_CAMERA:
                    if (mFile != null) {
                        ToastUtils.showToast(mFile.getAbsolutePath());
                    }
                    break;
                case REQUEST_ATTACH_VIDEO_GALLERY:
                    if (data != null) {
                        Uri uri = data.getData();
                        String path;

                        if (!TextUtils.isEmpty(uri.getAuthority())) {
                            path = mFileUtils.getRealPathFromURI(this, data.getData());
                        } else {
                            path = uri.getPath();
                        }

                        ToastUtils.showToast(path);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> permissionList) {
        //调用了一次拒绝权限认为失败
        if(requestCode == 1){
            ToastUtils.showToast("拒绝了权限" + permissionList.get(0));
            PermissionUtils.permissionDialog(this, permissionList, null);
        }
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }

        super.onBackPressed();
    }

    @Override
    public void onPause() {
        super.onPause();

        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void getChildView(int layoutId, View view) {
        Button record = (Button) view.findViewById(R.id.btn_record_video);
        Button select = (Button) view.findViewById(R.id.btn_select_from_gallery);
        Button cancel = (Button) view.findViewById(R.id.btn_cancel);

        record.setOnClickListener(this);
        select.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.top_return) {
            finish();
        } else if (id == R.id.btn_record_video) {
            PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else if (id == R.id.btn_select_from_gallery) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("video/*");
            startActivityForResult(intent, REQUEST_ATTACH_VIDEO_GALLERY);
        } else if (id == R.id.btn_cancel) {

        }

        if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
            mEasyPopupWindow.dismiss();
        }
    }
}
